//
//  ChatViewController.m
//  EaseMob
//
//  Created by wwj on 16/5/31.
//  Copyright © 2016年 wfw. All rights reserved.
//

#import "ChatViewController.h"
#import "EMMessageFrame.h"
#import "ChatViewCell.h"
#import "FWCustomTextView.h"
#import "NSString+Extend.h"
#import "EMCDDeviceManager.h"
#import "ChatHelper.h"
#import <IEMChatManager.h>
#import <EMSDK.h>

@interface ChatViewController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate, UITextViewDelegate, UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet FWCustomTextView *textView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *toolBarHeight;
@property (weak, nonatomic) IBOutlet UIButton *tockBtn;
@property (strong, nonatomic) EMConversation *conversation;
@property (strong, nonatomic) NSMutableArray *dataArray;
@property (copy, nonatomic) NSString *time;
@property (weak, nonatomic) IBOutlet UIView *buttomView;
@end

@implementation ChatViewController
static NSString *const ID = @"ID";

- (NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [ChatHelper sharedChatHelper].chatVC = self;
    
    self.navigationItem.title = self.titleStr;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWikkChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    [self.textView resignFirstResponder];
    self.textView.placeholder = @"输入新消息";
    
    [self.tableView registerClass:[ChatViewCell class] forCellReuseIdentifier:ID];
    
    //加载本地数据库的聊天记录
    [self loadLocalChatRecords];
   
}

- (IBAction)onClicTock:(UIButton *)sender {
    _tockBtn.hidden = !_tockBtn.isHidden;
    if (_tockBtn.isHidden == NO) {
        self.toolBarHeight.constant = 44;
        [self.view endEditing:YES];
        [sender setImage:[UIImage imageNamed:@"chatBar_keyboard"] forState:UIControlStateNormal];
    }else{
        [_textView becomeFirstResponder];
        [self textViewDidChange:_textView];
        [sender setImage:[UIImage imageNamed:@"chatBar_record"] forState:UIControlStateNormal];
    }
}

#pragma 开始录音
- (IBAction)beginRecord:(id)sender {
    int x = arc4random() % 100000;
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
    NSString *fileName = [NSString stringWithFormat:@"%d%d",(int)time,x];
    [[EMCDDeviceManager sharedInstance] asyncStartRecordingWithFileName:fileName completion:^(NSError *error) {
        if (!error) {
            MyLog(@"开始录音成功");
        }
    }];
}

#pragma 结束录音
- (IBAction)endRecord:(id)sender {
    [[EMCDDeviceManager sharedInstance] asyncStopRecordingWithCompletion:^(NSString *recordPath, NSInteger aDuration, NSError *error) {
        if (!error) {
            [self sendVoiceMessage:recordPath duration:aDuration];
        }
    }];
}

- (IBAction)cancelRecord:(id)sender {
    [[EMCDDeviceManager sharedInstance] cancelCurrentRecording];
}

- (IBAction)onClickAdd:(id)sender {
    //显示图片选择的控制器
    UIImagePickerController *imgPicker = [[UIImagePickerController alloc] init];
    
    // 设置源
    imgPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imgPicker.delegate = self;
    
    [self presentViewController:imgPicker animated:YES completion:NULL];
}

/**用户选中图片的回调*/
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    //1.获取用户选中的图片
    UIImage *selectedImg =  info[UIImagePickerControllerOriginalImage];
    
    //2.发送图片
    [self sendImageMessage:selectedImg];
    
    //3.隐藏当前图片选择控制器
    [self dismissViewControllerAnimated:YES completion:NULL];
    
}

- (void)keyBoardWikkChangeFrame:(NSNotification *)notification{
    CGRect keyboardF = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        self.buttomView.transform = CGAffineTransformMakeTranslation(0, keyboardF.origin.y - kScreenH);
    }];
    
}

#pragma mark ScrollView Delegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

- (void)textViewDidChange:(UITextView *)textView{
    CGFloat height = 0.0;
    CGFloat minHeight = 44;
    CGFloat maxHeight = 88;
    CGFloat contentHeight = textView.contentSize.height;
    if (contentHeight > maxHeight) {
        height = maxHeight;
    }else if (contentHeight < minHeight){
        height = minHeight;
    }else{
        height = contentHeight;
    }
    
    if ([textView.text hasSuffix:@"\n"]) {
        textView.text = [textView.text substringToIndex:textView.text.length - 1];
        [self sendTextMessage:textView.text];
        textView.text = nil;
        height = minHeight;
        [textView setContentOffset:CGPointZero animated:YES];
    }
    self.toolBarHeight.constant = height;
    [UIView animateWithDuration:0.2 animations:^{
        [self.view layoutIfNeeded];
    }];
}

#pragma mark TableView Delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat height = [self.dataArray[indexPath.row] height];
    return height;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ChatViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];
    cell.frameModel = self.dataArray[indexPath.row];
    return cell;
}

#pragma mark 加载本地数据库的聊天记录
- (void)loadLocalChatRecords{
    EMConversation *conversation = [[EMClient sharedClient].chatManager getConversation:self.conversaionID type:EMConversationTypeChat createIfNotExist:YES];
    self.conversation = conversation;
    __weak typeof(self) weakSelf = self;
    [conversation loadMessagesStartFromId:nil count:40 searchDirection:EMMessageSearchDirectionUp completion:^(NSArray *aMessages, EMError *aError) {
        if (aMessages.count == 0) return;
        [weakSelf addMessages:aMessages];
        [weakSelf reloadData];
    }];
    
}

- (void)reloadData{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.dataArray.count - 1 inSection:0];
    [self.tableView reloadData];
    // 滚动到最底部
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

- (void)didReceiveMessages:(NSArray *)aMessages{
    [self addMessages:aMessages];
    [self reloadData];
}

- (void)addMessages:(NSArray *)messages{
    NSMutableArray *fArray = [NSMutableArray array];
    for (EMMessage *message in messages) {
        EMMessageFrame *frameM = [self addMessage:message];
        if ([message.to isEqualToString:self.conversaionID]) {
            frameM.type = MessageTypeMe;
        }else{
            frameM.type = MessageTypeOther;
        }
        [_conversation markMessageAsReadWithId:message.messageId error:nil];
        frameM.message = message;
        [fArray addObject:frameM];
    }
    [self.dataArray addObjectsFromArray:fArray];
}

- (EMMessageFrame *)addMessage:(EMMessage *)message{
    EMMessageFrame *frameM = [[EMMessageFrame alloc] init];
    if ([message.to isEqualToString:self.conversaionID]) {
        frameM.type = MessageTypeMe;
    }else{
        frameM.type = MessageTypeOther;
    }
    NSString *timer = [NSString timeStr:message.timestamp];
    if (![_time isEqualToString:timer]) {
        frameM.time = timer;
        _time = timer;
        frameM.isHiden = NO;
    }else{
        frameM.isHiden = YES;
    }
    frameM.message = message;
    return frameM;
}

#pragma mark 发送文本消息
- (void)sendTextMessage:(NSString *)messageStr{
    EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithText:messageStr];
    [self sendMessage:body];
}

#pragma mark 发送语言消息
- (void)sendVoiceMessage:(NSString *)recordPath duration:(NSInteger)duration{
    EMVoiceMessageBody *body = [[EMVoiceMessageBody alloc] initWithLocalPath:recordPath displayName:@"[语言]"];
    body.duration = (int)duration;
    [self sendMessage:body];
}

#pragma mark 发送图片
- (void)sendImageMessage:(UIImage *)image{
    EMImageMessageBody *body = [[EMImageMessageBody alloc] initWithData:UIImagePNGRepresentation(image) displayName:@"[图片]"];
    [self sendMessage:body];
}

#pragma 发送消息
- (void)sendMessage:(EMMessageBody *)body{
    NSString *from = [[EMClient sharedClient] currentUsername];
    EMMessage *message = [[EMMessage alloc] initWithConversationID:self.conversation.conversationId from:from to:self.conversaionID body:body ext:nil];
    message.chatType = (EMChatType)self.chatType;
    [[EMClient sharedClient].chatManager sendMessage:message progress:nil completion:^(EMMessage *message, EMError *error) {
        if (!error) {
            [self.dataArray addObject:[self addMessage:message]];
            [self reloadData];
        }
    }];
}


- (void)dealloc{
    //移除消息回调
    [ChatHelper sharedChatHelper].chatVC = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
